package com.linln.modules.system.service;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.linln.common.utils.UUIDGenerator;
import com.linln.modules.system.dao.CustomMapper;
import com.linln.modules.system.dao.UserOrderMapper;
import com.linln.modules.system.dto.ExpressDto;
import com.linln.modules.system.entity.UserOrder;
import com.linln.modules.system.enums.WxParameter;
import com.linln.modules.system.vo.UserOrderDetailVO;
import com.linln.modules.system.vo.admins.OrderProductVo;
import com.linln.modules.system.vo.admins.UserOrderAddress;
import net.sf.jsqlparser.expression.operators.relational.RegExpMySQLOperator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;
import weixin.popular.api.PayMchAPI;
import weixin.popular.bean.paymch.MchOrderInfoResult;
import weixin.popular.bean.paymch.MchOrderquery;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;

@Service
public class UserOrderServices {

    @Autowired
    private UserOrderMapper userOrderMapper;

    @Autowired
    private CustomMapper customMapper;

    public Page<UserOrderDetailVO> getIndexUserOrder(Integer pageNum, Integer pageSize, String name, String mobile) {
        PageHelper.startPage(pageNum, pageSize, true);
        Page<UserOrderDetailVO> pager = userOrderMapper.getAllOrderDetailVo(name, mobile);
        long total = pager.getTotal();
        if (total > 0) {
            List<UserOrderDetailVO> result = pager.getResult();
            if(result.size()>0){
                for(int i =0;i<result.size();i++){
                    Integer states =   result.get(i).getTradeState();
                    int kinds = result.get(i).getKinds();
                    int kinds2 = result.get(i).getKinds2();
                    if(states == null){
                        Integer state = result.get(i).getStates();
                        if (state == 0) {
                            result.get(i).setStatus("待寄出");
                        } else if (state == 1) {
                            result.get(i).setStatus("已发货");
                        } else if (state == 2) {
                            result.get(i).setStatus("到店自取");
                        } else if (state == 4) {
                            result.get(i).setStatus("到店体验");
                        } else {
                            result.get(i).setStatus("未知");
                        }
                    } else if (states == 0) {
                        result.get(i).setStatus("待支付");
                    } else if (states == 1) {
                        result.get(i).setStatus("待发货");
                    } else if (states == 2) {
                        result.get(i).setStatus("已发货");
                    } else if (states == 3) {
                        result.get(i).setStatus("已完成");
                    } else if (states == 4) {
                        result.get(i).setStatus("已取消");
                    }else if (states == 5) {
                        result.get(i).setStatus("支付失败");
                    }else if (states == 6) {
                        result.get(i).setStatus("退款中");
                    }else if (states == 7) {
                        result.get(i).setStatus("已退款");
                    }else if (states == 8) {
                        result.get(i).setStatus("售后审核中");
                    }else if (states == 9) {
                        result.get(i).setStatus("审核通过");
                    }else if (states == 10) {
                        result.get(i).setStatus("审核未通过");
                    }else if (states == 11) {
                        result.get(i).setStatus("待体验");
                    }else if (states == 12) {
                        result.get(i).setStatus("待取件");
                    }else {
                        Integer state = result.get(i).getStates();
                        if (state == 0) {
                            result.get(i).setStatus("待寄出");
                        } else if (state == 1) {
                            result.get(i).setStatus("已发货");
                        } else if (state == 2) {
                            result.get(i).setStatus("到店自取");
                        } else if (state == 4) {
                            result.get(i).setStatus("到店体验");
                        } else {
                            result.get(i).setStatus("未知");
                        }
                    }
                    if(result.get(i).getUsername()==null){
                        result.get(i).setUsername(result.get(i).getContact());
                    }
                   String orderId=  result.get(i).getId();
                    Integer  subPoints = customMapper.getSubPoints(orderId);
                    result.get(i).setSurpluspoints(subPoints);
                }
            }
        /*    result.forEach(vo -> {
                Integer states = vo.getTradeState();
                int kinds = vo.getKinds();
                int kinds2 = vo.getKinds2();
              //  0 待支付 1待发货 2已发货 3已完成 4 已取消 5支付失败6退款中7已退款8售后审核中9审核通过10审核未通过11待体验12待取件
                if (states == 0) {
                    vo.setStatus("待支付");
                } else if (states == 1) {
                    vo.setStatus("待发货");
                } else if (states == 2) {
                    vo.setStatus("已发货");
                } else if (states == 3) {
                    vo.setStatus("已完成");
                } else if (states == 4) {
                    vo.setStatus("已取消");
                }else if (states == 5) {
                    vo.setStatus("支付失败");
                }else if (states == 6) {
                    vo.setStatus("退款中");
                }else if (states == 7) {
                    vo.setStatus("已退款");
                }else if (states == 8) {
                    vo.setStatus("售后审核中");
                }else if (states == 9) {
                    vo.setStatus("审核通过");
                }else if (states == 10) {
                    vo.setStatus("审核未通过");
                }else if (states == 11) {
                    vo.setStatus("待体验");
                }else if (states == 12) {
                    vo.setStatus("待取件");
                }else {
                    Integer state = vo.getStates();
                    if (state == 0) {
                        vo.setStatus("待寄出");
                    } else if (state == 1) {
                        vo.setStatus("已发货");
                    } else if (state == 2) {
                        vo.setStatus("到店自取");
                    } else if (state == 4) {
                        vo.setStatus("到店体验");
                    } else {
                        vo.setStatus("未知");
                    }
                }
                if(vo.getUsername()==null){
                    vo.setUsername(vo.getContact());
                }
            });*/
        }
        return pager;
    }

    //    public
    public UserOrderAddress userOrderAddressVoByOrderId(String userId, String orderId) {
        UserOrderAddress vo = customMapper.getUserOrderAddressVoByOrderId( orderId);
        return vo;
    }


     public OrderProductVo getOrderDetailById(String userId, String orderId) {
         OrderProductVo vo = customMapper.getOrderDetailById( orderId);
        return vo;
    }




    public int updateExpressOrder(String orderId,String expressCode,String expressCompany){
        UserOrder order = new UserOrder();
        order.setId(orderId).setExpressCode(expressCode)
                .setExpressCompany(expressCompany).setUpdateTime(new Date()).setTradeState(2);

        int update = userOrderMapper.updateByPrimaryKeySelective(order);
        return update;
    }

    public Map<String, Object> verifyOrder(String orderId) {

        UserOrder order = userOrderMapper.selectByPrimaryKey(orderId);
        String ordersCodes = order.getOrderCodes();
        Integer states = order.getTradeState();
        if (states == 0 ) {
            MchOrderquery mchOrderquery = new MchOrderquery();
            mchOrderquery.setAppid(WxParameter.appId);
            mchOrderquery.setMch_id(WxParameter.merchantId);
            mchOrderquery.setSign_type("MD5");
            mchOrderquery.setOut_trade_no(ordersCodes);
            mchOrderquery.setNonce_str(genaratorRandomString(32));

            MchOrderInfoResult result = PayMchAPI.payOrderquery(mchOrderquery, WxParameter.apiKey);

            String returnCode = result.getReturn_code();
            String result_code = result.getResult_code();
            String trade_state = result.getTrade_state();
            if ("SUCCESS".equals(returnCode) && "SUCCESS".equals(result_code)) {
                if ("SUCCESS".equals(trade_state)) { //支付成功
                    order.setTradeState(1);
                } else if ("NOTPAY".equals(trade_state)) { // 未支付
                    order.setTradeState(1);
                    // 啥也不干
                } else if ("PAYERROR".equals(trade_state)) { //支付失败(其他原因，如银行返回失败)
                    order.setTradeState(5);
                    // 啥也不干
                } else if ("CLOSED".equals(trade_state)) { // 已关闭
                    order.setTradeState(5);
                    // 啥也不干
                } else if ("REFUND".equals(trade_state)) { // 转入退款
                    order.setTradeState(7);
                    // 啥也不干
                }
                order.setUpdateTime(new Date());
                userOrderMapper.updateByPrimaryKeySelective(order);
            }
        }
        return null;
    }
    public String genaratorRandomString(int length) {
        String base = "abcdefghijklmnopqrstuvwxyz0123456789";
        Random random = new Random();
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < length; i++) {
            int number = random.nextInt(base.length());
            sb.append(base.charAt(number));
        }
        return sb.toString();
    }

    public int updateState(String orderId, String time) {
        int state =  userOrderMapper.updateState(orderId , time);
        return state;
    }

    public int delOrderById(String orderId) {
        int count =  userOrderMapper.delOrderById(orderId);
        return count;

    }

    public Integer getOrderStates(String orderId) {
        Integer tradeState =  userOrderMapper.getOrderStates(orderId);
        return tradeState;
    }
}
